package com.libc.yygh.hosp.config;


import com.libc.yygh.common.LoggerUtil;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

// @Configuration
public class MybatisConfig
{
    @Value ("${spring.datasource.jndi-name}")
    private String dataSourceJndiName;

    @Value ("${mybatis.mapper-locations}")
    private String mapperLocations;

    @Bean
    public SqlSessionFactoryBean createSqlSessionFactory( )
    {
        SqlSessionFactoryBean sqlSessionFactoryBean = null;
        try
        {
            // 加载JNDI配置
            Context context = new InitialContext();
            // DataSource dataSource = (DataSource) context.lookup(dataSourceJndiName);
            DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/spring_db");

            // 实例SessionFactory
            sqlSessionFactoryBean = new SqlSessionFactoryBean();
            // 配置数据源
            sqlSessionFactoryBean.setDataSource(dataSource);

            // 加载MyBatis配置文件
            PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
            // 能加载多个，所以可以配置通配符(如：classpath*:mapper/**/*.xml)
            sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources(mapperLocations));
            // 配置mybatis的config文件(我目前用不上)
            // sqlSessionFactoryBean.setConfigLocation("mybatis-config.xml");
        }
        catch (Exception e)
        {
            LoggerUtil.thr("创建SqlSession连接工厂错误：{}", e);
        }
        return sqlSessionFactoryBean;
    }
}